from django.shortcuts import render
from py2neo import *
import json

graph = Graph(
    'http://localhost:7474',
    auth=('neo4j', '12345678'),
    name='medical.db'
)  # 连接数据库


def get_disease_info(name):
    node = graph.run('MATCH(n{name:"' + name + '"}) return n').data()
    if len(node):
        this = json.dumps(node[0], ensure_ascii=False)
        this = json.loads(this)
        # name = str(this['n']['name'])
        # 就诊科室
        cure_department = str(this['n']['cure_department']).replace('[', '').replace(']', '').replace("'", '')
        # 描述
        desc = str(this['n']['desc'])
        # 发病原因
        cause = str(this['n']['cause'])
        # 治疗时长
        cure_lasttime = str(this['n']['cure_lasttime'])
        # 治疗方式
        cure_way = str(this['n']['cure_way']).replace('[', '').replace(']', '').replace("'", '')
        # 治愈率
        cured_prob = str(this['n']['cured_prob'])
        # 易感染人群
        easy_get = str(this['n']['easy_get'])
        # 防治方式
        prevent = str(this['n']['prevent'])

        # 获取该疾病的典型症状
        nodes_symptom = graph.run('MATCH(n{name:"' + name + '"})-[r:has_symptom]->(s:Symptom) return s').data()
        symptom_list = []
        for n in nodes_symptom:
            # 将节点信息的格式转化为json
            node = json.dumps(n, ensure_ascii=False)
            node = json.loads(node)
            # 取出节点信息中的name
            s_name = str(node['s']['name'])
            symptom_list.append(s_name)
        symptoms = '、'.join(symptom_list)

        disease_info = {
            'disease_info':
                [
                    # 1'疾病名称：' +
                    name,
                    # 2'就诊科室：' +
                    cure_department,
                    # 3'简单描述：' +
                    desc,
                    # 4'典型症状：' +
                    symptoms,
                    # 5'发病原因：' +
                    cause,
                    # 6'治疗时长：' +
                    cure_lasttime,
                    # 7'治疗方式：' +
                    cure_way,
                    # 8'治愈率：' +
                    cured_prob,
                    # 9'易感人群：' +
                    easy_get,
                    # 10'防治方式：' +
                    prevent
                ]
        }
        return disease_info
    else:
        return 0


def get_baike(request):
    disease_info = {
        'disease_info': ['您尚未输入疾病名称']
    }
    name = request.GET.get("name") or ""
    if name and name != "":
        if get_disease_info(name):
            disease_info = get_disease_info(name)
        else:
            disease_info = {
                'disease_info': ['您所查询的疾病不在数据库中']
            }
        return render(request, 'baike.html', disease_info)
    else:
        return render(request, 'baike.html')
